/**
 * 
 */
package com.ly.hotel.adaptor;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


//import com.ly.hotel.board.ADA801.NetworkAda801;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.SysConf;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

/**
 * @author jouson 2014-7-4
 */
public class NetworkUtil {

	public static boolean isWifiConnected(Context context) {
		boolean rv = false;
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mWiFiNetworkInfo = mConnectivityManager
					.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			if (mWiFiNetworkInfo != null) {
				rv = mWiFiNetworkInfo.isAvailable();
			}
		}
		return rv;
	}

	public static boolean checkEthernet(Context context) {
		ConnectivityManager conn =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = conn.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
		if (networkInfo != null && networkInfo.isConnected()) {
			return true;
		}

	    return false;
	}
	
	public static boolean isConnected(Context context) {
		
		if ((SysConf.extendConfGetValue(SysConf.SYS_CONF_CHECK_NET_ENABLE, "1").equals("0"))){
			return true;
		} else {
			Log.i("network","无线状态：：：" + isWifiConnected(context));
			Log.i("network","有线状态：：：" + checkEthernet(context));
			if (isWifiConnected(context)) {
				return true;
			}
			return checkEthernet(context);
		}
	}
	
	public static boolean isConnectednoLog(Context context) {
		if (isWifiConnected(context)) {
			return true;
		}
		return checkEthernet(context);
	}
	
	public static boolean isIpAddr(String ip){
		if(ip == null || ip.equals("")){
			return false;
		}
		Pattern pattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");

		Matcher matcher = pattern.matcher(ip); //以验证127.400.600.2为例
		
		Log.i("setting", "isIpAddr:" + matcher.matches());
		return matcher.matches();
	}
	
    /**
     * 检测外网是否连接
     *
     * @param con
     * @return
     */
    public static boolean isInternetAvailable(Context con) {
        ConnectivityManager cm = (ConnectivityManager) con
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null)
            return false;
        NetworkInfo netinfo = cm.getActiveNetworkInfo();
        if (netinfo == null) {
            return false;
        }
        if (netinfo.isConnected()) {
            return true;
        }
        return false;
    }

    public static void getNetworkState(Context con){
        //获取
        ConnectivityManager connectivityManager=
                (ConnectivityManager)con.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
        StringBuilder sb = new StringBuilder();
        sb.append("TypeName:").append(networkInfo.getTypeName()).append("\n");
        sb.append("Type:").append(networkInfo.getType()).append("\n");
        sb.append("isAvailable:").append(networkInfo.isAvailable()).append("\n");
        sb.append("isConnected:").append(networkInfo.isConnected()).append("\n");
        NetworkInfo.DetailedState state= networkInfo.getDetailedState();
        String detailedState="";
        if(state== NetworkInfo.DetailedState.AUTHENTICATING){
            detailedState="AUTHENTICATING";
        }else if(state== NetworkInfo.DetailedState.BLOCKED){
            detailedState="BLOCKED";
        }else if(state== NetworkInfo.DetailedState.CONNECTED){
            detailedState="CONNECTED";
        }else if(state== NetworkInfo.DetailedState.CONNECTING){
            detailedState="CONNECTING";
        }else if(state== NetworkInfo.DetailedState.DISCONNECTED){
            detailedState="DISCONNECTED";
        }else if(state== NetworkInfo.DetailedState.DISCONNECTING){
            detailedState="DISCONNECTING";
        }else if(state== NetworkInfo.DetailedState.FAILED){
            detailedState="FAILED";
        }else if(state== NetworkInfo.DetailedState.IDLE){
            detailedState="IDLE";
        }else if(state== NetworkInfo.DetailedState.SCANNING){
            detailedState="SCANNING";
        }else if(state== NetworkInfo.DetailedState.OBTAINING_IPADDR){
            detailedState="OBTAINING_IPADDR";
        }else if(state== NetworkInfo.DetailedState.SUSPENDED){
            detailedState="SUSPENDED";
        }
        
        Log.i("network", "DetailedState:" + detailedState);
    }

    /*
	* @author sichard
    * @category 判断是否有外网连接（普通方法不能判断外网的网络是否连接，比如连接上局域网）
    * @return
    */ 
    public static boolean ping(String url){
		String host = url;
 
		int len = 0;
		int exit = 0;
		Runtime runtime = Runtime.getRuntime();
		String cmd = "/system/bin/ping -q -c1 "+ host;
		Process process;
		try {
			process = runtime.exec(cmd);
			BufferedInputStream dummyBufIn = new BufferedInputStream(process.getInputStream());
			
			Log.e("init", "ping:" + host);

			while((len = dummyBufIn.available()) > 0){
				dummyBufIn.skip(len);
			}

			process.waitFor();
			exit = process.exitValue();
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		if(exit == 0){
			Log.e("init", host + "ping通了，好嗨皮啊！！");
			return true;
		} else{
			Log.e("init", host + "ping不通，用代理上网吧！！");
			return false;
		}
    }
    
  //测试对服务器的联通性，0表示正常，否则为异常
  	public static String pingHost(int times, String hostIp){
  		String rv = "";
//  		String host = MyApplication.getHostIp();
  		String host = hostIp;
//  		String host = "172.16.0.108";
  		//如果包括了端口的方式,如172.16.1.250:8081，就要去掉之
  		if(host.contains(":")){
  			String tmp [] = host.split(":");
  			host = tmp[0];
  		} 
  		
  		int len = 0;
  		int exit = 0;
  		Runtime runtime = Runtime.getRuntime();
  		String cmd = "/system/bin/ping -c " + times + " -W 1 " + host;//ping一次 等待1秒 -q可以隐藏过程
  		Process process;
  		try {
  			process = runtime.exec(cmd);
  			BufferedInputStream dummyBufIn = new BufferedInputStream(process.getInputStream());
  			
//  			Log.e("ping", "ping服务器:" + host);
  			
  			byte c [] = new byte[1024];
  			int n = 0;
  			while((n=dummyBufIn.read(c))!=-1){
  				String temp = new String(c,0,n);
//  				Log.e("ping", temp);
  				rv += temp;
  			}
  				
  			while((len = dummyBufIn.available()) > 0){
  				dummyBufIn.skip(len);
  			}
  	
  			process.waitFor();
  			exit = process.exitValue();
  			
  			//Log.e("ping", "exitValue:" + exit);
  			if(exit != 0){
  				rv = "-1";
  			}
  		} catch (IOException e) {
  			e.printStackTrace();
  		} catch (InterruptedException e) {
  			e.printStackTrace();
  		}
  	
  		if(exit == 0){
  			MyApplication.serverAssess = true;
//  			Log.e("ping", "服务器ping通了，好嗨皮啊！！");
  		} else{
  			MyApplication.serverAssess = false;
//  			Log.e("ping", "服务器ping不通，搞毛线！！");
  		}
  		return rv;
  	} 
  	
}
